import axios from "axios"; // 引用axios
import { Toast } from 'vant'


const request = axios.create({
    baseURL: process.env.NODE_ENV === "production" ? process.env.VUE_APP_BASE_API : "/api",
    timeout: 5000,
    withCredentials:true,
});

function startLoading() {
    // 开始加载
    Toast.loading({
        message: '加载中...',
        forbidClick: true,
        className:'toast',
        iconSize:'32px'
    });
}
function endLoading() {
    // 结束加载
    Toast.clear()
}
// 请求前
request.interceptors.request.use(config => {
    startLoading()
    return config
}, error => {
    Promise.reject(error)
})
// 请求后
request.interceptors.response.use(
    response => {
        endLoading()
        return Promise.resolve(response)
    },
    error => {
        startLoading()
        // if (error.response) {
        //     switch (error.response.status) {
        //         case 401:
        //             console.log(401)
        //             break;
        //         case 403:
        //             console.log(403)
        //             break;
        //         case 404:
        //             Toast({
        //                 message: '网络请求不存在',
        //                 duration: 1500,
        //                 forbidClick: true
        //             })
        //             console.log(404)
        //             break;
        //         case 500:
        //             console.log(500)
        //             break;
        //     }
        // }
        return Promise.reject(error.response)
    }
)
//get请求
export function get(url, params = {}) {
    return new Promise((resolve, reject) => {
        request
            .get(url, {
                params: params,
            })
            .then((response) => {
                resolve(response);
            })
            .catch((err) => {
                reject(err);
            });
    });
}
//post请求
export function post(url, data = {}) {
    return new Promise((resolve, reject) => {
        request.post(url, data).then(
            (response) => {
                resolve(response.data);
            },
            (err) => {
                reject(err);
            }
        );
    });
}
//put请求
export function put(url, data = {}) {
    return new Promise((resolve, reject) => {
        request.post(url, data).then(
            (response) => {
                resolve(response.data);
            },
            (err) => {
                reject(err);
            }
        );
    });
}

export default {
    get,
    post,
    put,
}
